package com.wzcl.app.service.impl;

import com.wzcl.app.dao.model.AppUser;
import com.wzcl.app.dao.model.SendPath;
import com.wzcl.app.dao.repository.SendPathRepository;
import com.wzcl.app.model.common.BusinessException;
import com.wzcl.app.model.common.CodeMsg;
import com.wzcl.app.model.common.MyPage;
import com.wzcl.app.model.common.WZCL;
import com.wzcl.app.model.dto.SendPathDto;
import com.wzcl.app.service.SendPathService;
import com.wzcl.app.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Log4j2
@Service
public class SendPathServiceImpl implements SendPathService {

    @Autowired
    private SendPathRepository repository;

    @Autowired
    private UserService userService;

    @Override
    public SendPath addSendPath(SendPathDto sendPathDto) {
        SendPath sendPath = new SendPath();
        BeanUtils.copyProperties(sendPathDto, sendPath, "id", "path", "userId", "userPhone", "state");
        //校验获取用户
        AppUser user = userService.getAndCheckByPhone(sendPathDto.getUserPhone());
        //创建
        sendPath.setPath(StringUtils.join(sendPathDto.getPath(), ","));
        sendPath.setUserId(user.getId());
        sendPath.setUserPhone(user.getPhone());
        sendPath.setState(WZCL.STATE.NOT_DELETE);
        if (sendPath.getIsDefault()) {
            delDefaultPath(sendPathDto.getUserPhone());
        }
        return repository.save(sendPath);
    }

    @Override
    public SendPath delSendPath(SendPathDto sendPathDto) {
        //校验获取
        SendPath sendPath = getAndCheckById(sendPathDto);
        //用户校验
        if (!sendPath.getUserPhone().equals(sendPathDto.getUserPhone())) {
            throw new BusinessException(CodeMsg.USER_NOT_MATCH);
        }
        sendPath.setState(WZCL.STATE.IS_DELETE);
        sendPath.setIsDefault(false);
        log.info("SendPath ID:{} logic deletion", sendPath.getId());
        repository.save(sendPath);
        return sendPath;
    }

    @Override
    public SendPath updateSendPath(SendPathDto sendPathDto) {
        //校验获取
        SendPath sendPath = getAndCheckById(sendPathDto);
        //用户校验
        if (!sendPath.getUserPhone().equals(sendPathDto.getUserPhone())) {
            throw new BusinessException(CodeMsg.USER_NOT_MATCH);
        }
        //若修改的地址为默认地址 则删除用户之前的默认地址标识
        if (sendPathDto.getIsDefault() && !sendPath.getIsDefault()) {
            delDefaultPath(sendPath.getUserPhone());
        }
        //修改
        BeanUtils.copyProperties(sendPathDto, sendPath, "id", "userId", "userPhone", "state");
        sendPath.setPath(StringUtils.join(sendPathDto.getPath(), ","));
        //校验默认地址
        return repository.save(sendPath);
    }

    @Override
    public SendPath getSendPathById(Integer id) {
        return repository.findById(id).orElse(null);
    }


    @Override
    public SendPath getAndCheckById(Integer id) {
        if (id == null) {
            throw new BusinessException(CodeMsg.MUST_BE_NOT_NULL, "缺少配送地址ID");
        }
        SendPath sendPath = getSendPathById(id);
        if (sendPath == null) {
            throw new BusinessException(CodeMsg.SEND_PATH_NOT_EXIST);
        }
        return sendPath;
    }

    @Override
    public SendPath getAndCheckDefaultByPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new BusinessException(CodeMsg.MUST_BE_NOT_NULL, "缺少用户手机");
        }
        SendPath sendPath = repository.findDefaultPathByUserPhone(phone);
        if (sendPath == null) {
            throw new BusinessException(CodeMsg.SEND_PATH_NOT_EXIST);
        }
        return sendPath;
    }

    @Override
    public SendPath getDefaultByPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new BusinessException(CodeMsg.MUST_BE_NOT_NULL, "缺少用户手机");
        }
        return repository.findDefaultPathByUserPhone(phone);
    }

    @Override
    public List<SendPath> getSendPathList(SendPathDto sendPathDto) {
        return repository.findAll(getSpecification(sendPathDto), sendPathDto.getSort());
    }

    @Override
    public MyPage<SendPath> getSendPathPage(SendPathDto sendPathDto) {
        return new MyPage<>(repository.findAll(getSpecification(sendPathDto), sendPathDto.getPageable()));
    }

    @Override
    @Transactional
    public SendPath setDefaultPath(SendPathDto sendPathDto) {
        //校验获取
        SendPath sendPath = getAndCheckById(sendPathDto);
        //用户校验
        if (!sendPath.getUserPhone().equals(sendPathDto.getUserPhone())) {
            throw new BusinessException(CodeMsg.USER_NOT_MATCH);
        }
        //已经是默认地址直接返回
        if (sendPath.getIsDefault()) {
            return sendPath;
        }
        //删除之前的默认地址标识
        delDefaultPath(sendPathDto.getUserPhone());
        sendPath.setIsDefault(true);
        log.info("用户{}设置Id{}收获地址为默认地址", sendPathDto.getUserPhone(), sendPath.getId());
        return repository.save(sendPath);
    }

    public void delDefaultPath(String userPhone) {
        SendPath defaultPath = repository.findDefaultPathByUserPhone(userPhone);
        if (defaultPath != null) {
            defaultPath.setIsDefault(false);
            log.info("用户{}取消Id{}收获地址为默认地址", userPhone, defaultPath.getId());
            repository.save(defaultPath);
        }
    }

    private Specification<SendPath> getSpecification(SendPathDto sendPathDto) {
        return new Specification<SendPath>() {
            @Override
            public Predicate toPredicate(Root<SendPath> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(sendPathDto.getUserPhone())) {
                    predicates.add(criteriaBuilder.equal(root.get("userPhone"), sendPathDto.getUserPhone()));
                }
                predicates.add(criteriaBuilder.equal(root.get("state"), WZCL.STATE.NOT_DELETE));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }
}
